package com.onekbase.demo.mybatis;

import com.onekbase.demo.mybatis.mapper.SysConfigMapper;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.Properties;

public class D02BuildFromCodeMain {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("driver","com.mysql.jdbc.Driver");
        props.put("url","jdbc:mysql://localhost:3306/test");
        props.put("username","root");
        props.put("password","123456");
        DataSourceFactory dsFactory = new PooledDataSourceFactory();
//        DataSourceFactory dsFactory = new UnpooledDataSourceFactory();
        dsFactory.setProperties(props);
        DataSource dataSource = dsFactory.getDataSource();
        TransactionFactory txFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", txFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(SysConfigMapper.class);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(configuration);

        try (SqlSession session = factory.openSession()) {
            Object o = session.selectOne("com.onekbase.demo.mybatis.mapper.SysConfigMapper.selectConfig", "key.hello");
            System.out.println(o);
        }
    }
}
